package org.zffc.handler;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Note:
 * @Author: zhangfei
 * @Date: 2025/2/24 17:02
 **/
@Configuration
public class SentinelBlockHandler {
    @PostConstruct
    public void initBlockHandlers() {
        // 自定义限流/熔断处理逻辑
        BlockRequestHandler blockHandler = (exchange, ex) -> {
            Map<String, String> response = new HashMap<>();
            if (ex instanceof FlowException) {
                // 限流异常
                response.put("code", "429");
                response.put("message", "请求过多，请稍后再试（限流）");
            } else if (ex instanceof DegradeException) {
                // 熔断异常
                response.put("code", "503");
                response.put("message", "服务暂时不可用，请稍后再试（熔断）");
            }else if (ex instanceof ParamFlowException) {
                // 热点参数限流
                response.put("code", "504");
                response.put("message", "热点参数限流，请稍后再试");
            } else if (ex instanceof AuthorityException) {
                // 黑名单
                response.put("code", "505");
                response.put("message", "无权限访问");
            }else if (ex instanceof SystemBlockException) {
                // 黑名单
                response.put("code", "506");
                response.put("message", "系统自适应保护");
            }


            return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(BodyInserters.fromValue(response));
        };
        // 设置全局异常处理器
        GatewayCallbackManager.setBlockHandler(blockHandler);
    }
}
